<?php
namespace app\controller;

use app\BaseController;
use \think\facade\Request;
use app\command\ComModel;
use \think\facade\Cache;
use \think\facade\Db;
use \think\facade\Log;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QRCodeException;
use PhpOffice\PhpSpreadsheet\Shared\CodePage;

class Admin extends BaseController
{
    public function login1()
    {
        $param = Request::param();
		$redis = Cache::store('redis');
        if($param['uname']=='admin' && $param['upwd']=='123456'){
				$token = bin2hex(random_bytes(32));
				$redis->set($token, -1,36000);
                $dd = [
                    'token'=>$token,
                    'company_name'=>'admin'
                ];
				$this->returnJson(200,'登录成功',$dd);
		}else{
				$this->returnJson(400,'账户密码输入错误',[]);
		}
    }
    // 修改密码
	public function updateUpwd()
	{
		$param = Request::param();
		$id = $this->getAdminId();
        
		$res = Db::name('yh_company')
			->field('id,uname,upwd')
			->where('id',$id)
			->find();
		if($res['upwd'] != md5($param['oldPassword'])){
		  return	$this->returnJson(400,'旧密码错误',[]);
		}
		if($param['confirmPassword'] != $param['newPassword']){
		  return	$this->returnJson(400,'两次密码不一致',[]);
		}
		Db::name('yh_company')->where('id',$id)->update(['upwd'=>md5($param['newPassword'])]);
		return $this->returnJson(200,'操作成功',[]);
	}
     // 商家后台登录
    public function login()
    {
        
        $data = Request::post();
        $data['upwd'] = md5($data['upwd']);
        $redis = Cache::store('redis');
        $code = strtoupper($data['code']);
        $bool =  $redis->get($code);
        if(!$bool){
            return $this->returnJson(400,'验证码错误',[]);
        }
        unset($data['code']);
        $res = Db::name('yh_company')
                ->where($data)
                ->whereNull('delete_time')
                ->find();
        if(!$res){
            return $this->returnJson(400,'账号已被删除',[]);
        }
        if($res['mark'] == 0){
            return $this->returnJson(400,'账号已被禁用',[]);
        }

        if($res){
            $token = bin2hex(random_bytes(32));
				$redis->set($token, $res['id'],36000);
                $dd = [
                    'token'=>$token,
                    'company_name'=>$res['company_name'],
                    'job_id'=>$res['job']
                ];
				$this->returnJson(200,'登录成功',$dd);
        }else{ 
             return $this->returnJson(400,'账号密码错误',[]);
        }
    }
    public function addEditGoods(){
        $param = Request::param();
        if($param['id']){
            $param['update_time'] = date("Y-m-d H:i:s");
            Db::name('goods')
                        ->where('id',$param['id'])
                        ->update($param);
            $this->returnJson(200,'操作成功',[]);
        }else{
            $param['add_time'] = date("Y-m-d H:i:s");
            $param['update_time'] = date("Y-m-d H:i:s");
            Db::name('goods')
                    ->insert($param);
            $this->returnJson(200,'操作成功',[]);
        }
    }
    public function getGoodsList(){
        $param = Request::param();
        if(isset($param['page'])){
            $page=$param['page'];
            $pageSize = $param['pageSize'];
            $page=($page-1)*$pageSize;
            $list = Db::name('goods')
                ->limit($page,$pageSize)
                ->order('id','desc')
                ->whereNull('delete_time')
                ->select();
        }else{
            $list = Db::name('goods')
                ->order('id','desc')
                ->whereNull('delete_time')
                ->select();
        }
        
        $count = Db::name('goods')
                ->whereNull('delete_time')
                ->count();

        $dd = [
            'result'=>$list,
            'count'=>$count
        ];
        $this->returnJson(200,'操作成功',$dd);
    }
    // 删除商品
    public function delGoods(){
        $param = Request::param();
        $dd = $param['dd'];
        Db::name('goods')
                ->where('id',$dd['id'])
                ->useSoftDelete('delete_time',time())
                ->delete();
        $this->returnJson(200,'操作成功',[]);
    }
    // 添加二维码
    public function addQrCode(){
        try {
            Db::startTrans();
            $param = Request::param();
            $number = $param['number'];
            $num = $param['num'];
            $addTime = date("Y-m-d H:i:s");
            $updateTime = date("Y-m-d H:i:s");
            
            for($i=0;$i<$number;$i++){
                try {
                    // 生成唯一的主表二维码编号
                    $qrSnP = createOrderSn1();
                    $dd1 = [
                        'goods_id' => $param['goods_id'],
                        'add_time' => $addTime,
                        'update_time' => $updateTime,
                        'qr_sn' => $qrSnP,
                        'bath' => $param['bath'],
                    ];
                    $pid = Db::name('qrcode_p')->insertGetId($dd1);
                    
                    // 生成子表二维码数据
                    $batchData = [];
                    for($j=0;$j<$num;$j++){
                        $batchData[] = [
                            'pid' => $pid,
                            'goods_id' => $param['goods_id'],
                            'add_time' => $addTime,
                            'update_time' => $updateTime,
                            'qr_sn' => createOrderSn1(),
                            'bath' => $param['bath'],
                        ];
                    }
                    
                    // 尝试批量插入子表
                    try {
                        Db::name('qrcode')->insertAll($batchData);
                    } catch (\Exception $batchE) {
                        // 批量插入失败时转为单条插入，跳过重复数据
                        foreach($batchData as $qrData) {
                            try {
                                Db::name('qrcode')->insert($qrData);
                            } catch (\Exception $singleE) {
                                // 记录单条插入失败日志（可能是重复qr_sn）
                                Log::error('单条插入二维码失败，跳过该记录：' . $singleE->getMessage() . '，数据：' . json_encode($qrData));
                                continue; // 跳过当前重复数据
                            }
                        }
                    }
                } catch (\Exception $e) {
                    // 记录主表插入失败日志（可能是重复qr_sn）
                    Log::error('插入主表二维码失败，跳过该组记录：' . $e->getMessage());
                    continue; // 跳过当前组，继续下一组插入
                }
            }
            
            Db::commit();
            $this->returnJson(200,'操作成功',[]);
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('二维码生成失败（事务回滚）：' . $e->getMessage() . ', 堆栈信息：' . $e->getTraceAsString());
            $this->returnJson(500,'操作失败，已回滚：' . $e->getMessage(),[]);
        }
    }
    // 获取二维码列表
    public function getQrcodeList(){
        $param = Request::param();
        $searchForm = $param['searchForm'];
        $map = [];
        if(isset($searchForm['bath'])){
            $map[] = ['bath','like','%'.$searchForm['bath'].'%'];
        }
        if(isset($searchForm['status'])){
            if($searchForm['status']!=-1){
                $map[] = ['status','=',$searchForm['status']];
            }
        }
    
        if(isset($searchForm['start_time']) && isset($searchForm['end_time'])){
            if($searchForm['start_time']!='' && $searchForm['end_time']!=''){
                $map[] = ['add_time','>=',$searchForm['start_time'].' 00:00:00'];
                 $map[] = ['add_time','<=',$searchForm['end_time'].' 23:59:59'];
            }
        }
        $page=$param['page'];
        $pageSize = $param['pageSize'];
        $page=($page-1)*$pageSize;
        $result = Db::name('qrcode_p')
            ->limit($page,$pageSize)
            ->order('id','desc')
            ->where($map)
            ->whereNull('delete_time')
            ->select()
            ->all();
        
        $count = Db::name('qrcode_p')
                ->where($map)
                ->whereNull('delete_time')
                ->count();
        foreach($result as $key=>$val){
            $result[$key]['goods_name'] = Db::name('goods')
                ->where('id',$val['goods_id'])
                ->value('goods_name');
            $result[$key]['hasChildren'] = true;
            $result[$key]['list'] = Db::name('qrcode')
                ->where($map)
                ->where('pid',$val['id'])
                ->whereNull('delete_time')
                ->select()
                ->all();
        }

        $dd = [
            'result'=>$result,
            'count'=>$count
        ];
        $this->returnJson(200,'操作成功',$dd);
    }
    // 删除二维码
    public function delQrCode(){
        $param = Request::param();
        $dd = $param['dd'];
        Db::name('qrcode')
                ->where('id',$dd['id'])
                ->useSoftDelete('delete_time',time())
                ->delete();
        Db::name('qrcode')
                ->where('pid',$dd['id'])
                ->useSoftDelete('delete_time',time())
                ->delete();
        $this->returnJson(200,'操作成功',[]);
    }
    // 用户列表
    public function getUserList(){
        $param = Request::param();
        $searchForm = $param['searchForm'];
        $map = [];
        if(isset($searchForm['area'])){
            if($searchForm['area']!=''){
                $map[] = ['area','like','%'.$searchForm['area'].'%'];
            }
        }
        if(isset($searchForm['city'])){
            if($searchForm['city']!=''){
                $map[] = ['city','like','%'.$searchForm['city'].'%'];
            }
        }
        if(isset($searchForm['nick_name'])){
            if($searchForm['nick_name']!=''){
                $map[] = ['nick_name','like','%'.$searchForm['nick_name'].'%'];
            }
        }
        if(isset($searchForm['phone'])){
            if($searchForm['phone']!=''){
                $map[] = ['phone','like','%'.$searchForm['phone'].'%'];
            }
        }
        if(isset($searchForm['province'])){
            if($searchForm['province']!=''){
                $map[] = ['province','like','%'.$searchForm['province'].'%'];
            }
        }
        if(isset($searchForm['role'])){
            if($searchForm['role']!='-1'){
                $map[] = ['role','=',$searchForm['role']];
            }
        }
        // 筛选 age>small_age 并且 age<big_age
        if(isset($searchForm['small_age']) && isset($searchForm['big_age'])){
            if($searchForm['small_age']!='' && $searchForm['big_age']!=''){
                $map[] = ['age','>=',$searchForm['small_age']];
                 $map[] = ['age','<=',$searchForm['big_age']];
            }
        }
        // 筛选 add_time 在 start_time 和 end_time 之间
        if(isset($searchForm['start_time']) && isset($searchForm['end_time'])){
            if($searchForm['start_time']!='' && $searchForm['end_time']!=''){
                $map[] = ['add_time','>=',$searchForm['start_time'].' 00:00:00'];
                 $map[] = ['add_time','<=',$searchForm['end_time'].' 23:59:59'];
            }
        }
       
        $page=$param['page'];
        $pageSize = $param['pageSize'];
        $page=($page-1)*$pageSize;
        $list = Db::name('users')
            ->limit($page,$pageSize)
            ->order('id','desc')
            ->where($map)
            ->whereNull('delete_time')
            ->select()
            ->all();
        
        foreach($list as $key=>&$val){
            if($val['role']==1){
                $point = Db::table('point_water')
                    ->where('user_id',$val['id'])
                    ->sum('points');
            }
            if($val['role']==2){
                $point = Db::table('point_water_hzs')
                    ->where('user_id',$val['id'])
                    ->sum('points');
            }
            if($val['role']==3){
                $point = 0;
            }
             Db::table('users')
                ->where('id',$val['id'])
                ->update(['point'=>$point]);
        }

        
        $count = Db::name('users')
                ->where($map)
                ->whereNull('delete_time')
                ->count();

        $dd = [
            'result'=>$list,
            'count'=>$count
        ];
        $this->returnJson(200,'操作成功',$dd);
    }
    // 修改用户信息
    public function updateUser(){
        $dd = Request::param();
        $dd['update_time'] = date("Y-m-d H:i:s");
        Db::name('users')
                ->where('id',$dd['id'])
                ->update($dd);
        $this->returnJson(200,'操作成功',[]);
    }
    // 删除用户
    public function delUser(){
        $param = Request::param();
        $dd = $param['dd'];
        Db::name('users')
                ->where('id',$dd['id'])
                ->useSoftDelete('delete_time',time())
                ->delete();
        $this->returnJson(200,'操作成功',[]);
    }
    // 添加编辑用户地址
    public function addEditAddress(){
        $dd = Request::param();
        if($dd['id']==''){
            $dd['add_time'] = date("Y-m-d H:i:s");
            $dd['update_time'] = date("Y-m-d H:i:s");
            Db::name('address')
                    ->insert($dd);
        }else{
            $dd['update_time'] = date("Y-m-d H:i:s");
            Db::name('address')
                    ->where('id',$dd['id'])
                    ->update($dd);
        }
        $this->returnJson(200,'操作成功',[]);
    }
    // 用户地址列表
    public function getAddressList(){
        $param = Request::param();
        $searchForm = $param['searchForm'];
        $map = [];
        if(isset($searchForm['area']) && $searchForm['area']!=''){
            $map[] = ['area','like','%'.$searchForm['area'].'%'];
        }
        if(isset($searchForm['city']) && $searchForm['city']!=''){
            $map[] = ['city','like','%'.$searchForm['city'].'%'];
        }
        if(isset($searchForm['name']) && $searchForm['name']!=''){
            $map[] = ['name','like','%'.$searchForm['name'].'%'];
        }
        if(isset($searchForm['phone']) && $searchForm['phone']!=''){
            $map[] = ['phone','like','%'.$searchForm['phone'].'%'];
        }
        if(isset($searchForm['province']) && $searchForm['province']!=''){
            $map[] = ['province','like','%'.$searchForm['province'].'%'];
        }
        // 筛选 add_time 在 start_time 和 end_time 之间
        if(isset($searchForm['start_time']) && isset($searchForm['end_time'])){
            if($searchForm['start_time']!='' && $searchForm['end_time']!=''){
                $map[] = ['add_time','>=',$searchForm['start_time'].' 00:00:00'];
                 $map[] = ['add_time','<=',$searchForm['end_time'].' 23:59:59'];
            }
        }

        $page=$param['page'];
        $pageSize = $param['pageSize'];
        $page=($page-1)*$pageSize;
        $list = Db::name('address')
            ->limit($page,$pageSize)
            ->order('id','desc')
            ->where($map)
            ->whereNull('delete_time')
            ->select();
        
        $count = Db::name('address')
                ->where($map)
                ->whereNull('delete_time')
                ->count();
                
        $dd = [
            'result'=>$list,
            'count'=>$count
        ];
        $this->returnJson(200,'操作成功',$dd);
    }
    // 删除用户地址
    public function delAddress(){
        $param = Request::param();
        $dd = $param['dd'];
        Db::name('address')
                ->where('id',$dd['id'])
                ->useSoftDelete('delete_time',time())
                ->delete();
        $this->returnJson(200,'操作成功',[]);
    }
    // 奖品列表
    public function getPrizeList(){
        $param = Request::param();
        $searchForm = $param['searchForm'];
        $map = [];
        if(isset($searchForm['name']) && $searchForm['name']!=''){
            $map[] = ['name','like','%'.$searchForm['name'].'%'];
        }
        
        // 如果有分页分页查询没有分页不分页
        if(isset($param['page']) && isset($param['pageSize'])){
            $page=$param['page'];
            $pageSize = $param['pageSize'];
            $page=($page-1)*$pageSize;
            $list = Db::name('award')
                ->limit($page,$pageSize)
                ->order('id','desc')
                ->where($map)
                ->whereNull('delete_time')
                ->select();
        }else{
            $list = Db::name('award')
                ->order('id','desc')
                ->where($map)
                ->whereNull('delete_time')
                ->select();
        }
        
        $count = Db::name('award')
                ->where($map)
                ->whereNull('delete_time')
                ->count();
                
        $dd = [
            'result'=>$list,
            'count'=>$count 
        ];
        $this->returnJson(200,'操作成功',$dd);
    }
    // 添加更新奖品
    public function addEditPrize(){
        $dd = Request::param();
        if($dd['id']==''){
            $dd['add_time'] = date("Y-m-d H:i:s");
            $dd['update_time'] = date("Y-m-d H:i:s");
            Db::name('award')
                    ->insert($dd);
        }else{
            $dd['update_time'] = date("Y-m-d H:i:s");
            Db::name('award')
                    ->where('id',$dd['id'])
                    ->update($dd);
        }
        $this->returnJson(200,'操作成功',[]);
    }
    // 删除奖品
    public function delPrize(){
        $param = Request::param();
        $dd = $param['dd'];
        Db::name('award')
                ->where('id',$dd['id'])
                ->useSoftDelete('delete_time',time())
                ->delete();
        $this->returnJson(200,'操作成功',[]);
    }
    // 获取中奖记录
    public function getAwardHistoryList(){
        $param = Request::param();
        $searchForm = $param['searchForm'];
        $map = [];
        if(isset($searchForm['uid']) && $searchForm['uid']!=''){
            $map[] = ['uid','=',$searchForm['uid']];
        }
        if(isset($searchForm['aid']) && $searchForm['aid']!=''){
            $map[] = ['aid','=',$searchForm['aid']];
        }
        if(isset($searchForm['start_time']) && isset($searchForm['end_time'])){
            if($searchForm['start_time']!='' && $searchForm['end_time']!=''){
                $map[] = ['add_time','>=',$searchForm['start_time'].' 00:00:00'];
                 $map[] = ['add_time','<=',$searchForm['end_time'].' 23:59:59'];
            }
        }
        $page=$param['page'];
        $pageSize = $param['pageSize'];
        $page=($page-1)*$pageSize;
        $list = Db::name('award_history')
            ->limit($page,$pageSize)
            ->order('id','desc')
            ->where($map)
            ->whereNull('delete_time')
            ->select()
            ->all();
        foreach($list as $key=>$item){
            // 用户名 和 奖品名
            $list[$key]['nick_name'] = Db::name('users')
                    ->where('id',$item['uid'])
                    ->value('nick_name');
            $list[$key]['award_name'] = Db::name('award')
                    ->where('id',$item['aid'])
                    ->value('name');
            $list[$key]['address_info'] = Db::name('user_address')
                    ->where('id',$item['address_id'])
                    ->find();
         }
            
        $count = Db::name('award_history')
                ->where($map)
                ->whereNull('delete_time')
                ->count();
                
        $dd = [
            'result'=>$list,
            'count'=>$count 
        ];
        $this->returnJson(200,'操作成功',$dd);
    }
    // 删除中奖记录
    public function delAwardHistory(){
        $param = Request::param();
        $dd = $param['dd'];
        Db::name('award_history')
                ->where('id',$dd['id'])
                ->useSoftDelete('delete_time',time())
                ->delete();
        $this->returnJson(200,'操作成功',[]);
    }
    // 获取奖励描述
    public function getRewardDesc(){
        $param = Request::param();
        $desc = Db::name('reward_desc')
                ->where('cid',1)
                ->find();
        $this->returnJson(200,'操作成功',$desc);
    }
    // 设置奖励描述
    public function setRewardDesc(){
        $param = Request::param();
        Db::name('reward_desc')
                ->where('cid',1)
                ->update($param);
        $this->returnJson(200,'操作成功',[]);
    }
     // 订单详情
    public function getOrderInfo()
    {
       $param = Request::param();
        $id = $param['id'];
        $order_info = Db::table('order_info')
                                ->where('id',$id)
                                ->find();
        $address_info = Db::table('address')
                                ->where('id',$order_info['address_id'])
                                ->find();
        $order_info['address_info'] = $address_info;
        return $this->returnJson(200,'操作成功',$order_info);
    }
    // 删除订单
    public function deleteOrder()
    {
       $param = Request::param();
        $id = $param['id'];
         $res =  Db::name('order_info')
                ->where('id',$id)
                ->useSoftDelete('delete_time',time())
                ->delete();
        if($res){
            return $this->returnJson(200,'操作成功',[]);
        }else{
            return $this->returnJson(400,'操作失败',[]);
        }
    }
	// 获取订单列表
	public function getOrderList()
	{
		$param = Request::param();
        $user_id = $this->getUserId();
		$page = $param['page'];
		$pageSize = $param['pageSize'];
        $searchForm = $param['searchForm'];
        $map = [];
        if(isset($searchForm['start_time']) && isset($searchForm['end_time'])){
            if($searchForm['start_time']!='' && $searchForm['end_time']!=''){
                $map[] = ['add_time','>=',$searchForm['start_time'].' 00:00:00'];
                 $map[] = ['add_time','<=',$searchForm['end_time'].' 23:59:59'];
            }
        }
        if(isset($searchForm['status']) && $searchForm['status']!='-1'){
            $map[] = ['status','=',$searchForm['status']];
        }
        if(isset($searchForm['type']) && $searchForm['type']!='-1'){
            $map[] = ['type','=',$searchForm['type']];
        }
        if(isset($searchForm['role']) && $searchForm['role']!='-1'){
            $map[] = ['role','=',$searchForm['role']];
        }
        if(isset($searchForm['delivery_name']) && $searchForm['delivery_name']!=''){
            $map[] = ['delivery_name','like','%'.$searchForm['delivery_name'].'%'];
        }
        if(isset($searchForm['deliveryCode']) && $searchForm['deliveryCode']!=''){
            $map[] = ['deliveryCode','like','%'.$searchForm['deliveryCode'].'%'];  
        }
        if(isset($searchForm['payType']) && $searchForm['payType']!='-1'){
            $map[] = ['pay_type','=',$searchForm['payType']];
        }

		$list = Db::table('order_info')
					->where($map)
					->order('id','desc')
					->page($page,$pageSize)
                    ->whereNull('delete_time')
					->select()
					->all();
        foreach($list as $k=>$v){
            $list[$k]['spec'] = Db::table('goods')
                                ->where('id',$v['goods_id'])
                                ->value('spec');
            $list[$k]['address_info'] = Db::table('user_address')
                                ->where('id',$v['address_id'])
                                ->find();
        }
		$count = Db::table('order_info')
					->where($map)
                    ->whereNull('delete_time')
					->count();
		$res = [
			'result'=>$list,
			'count'=>$count
		];
		return $this->returnJson(200,'操作成功',$res);
	}
    // 编辑订单
    public function editOrder()
    {
        $param = Request::param();
        $id = $param['id'];
        if($param['status']==3){
            $param['send_time'] = date('Y-m-d H:i:s');
        }
        Db::name('order_info')
                ->where('id',$id)
                ->update($param);
        $this->returnJson(200,'操作成功',[]);
    }
    // 编辑中奖记录
    public function editWinRecord(){
        $param = Request::param();
        $id = $param['id'];
        Db::name('award_history')
                ->where('id',$id)
                ->update($param);
        $this->returnJson(200,'操作成功',[]);
    }
    // 删除订单
    public function delOrder(){
       $param = Request::param();
        $dd = $param['dd'];
        Db::name('order_info')
                ->where('id',$dd['id'])
                ->useSoftDelete('delete_time',time())
                ->delete();
        $this->returnJson(200,'操作成功',[]);
    }
    // 获取积分明细
  public function getPointExchangeDetail()
  {
    $param = Request::param();
    $page=$param['page'];
    $pageSize = $param['pageSize'];
    $page=($page-1)*$pageSize;
    $searchForm = $param['searchForm'];
    $map = [];
    if(isset($searchForm['start_time']) && isset($searchForm['end_time'])){
        if($searchForm['start_time']!='' && $searchForm['end_time']!=''){
            $map[] = ['add_time','>=',$searchForm['start_time'].' 00:00:00'];
             $map[] = ['add_time','<=',$searchForm['end_time'].' 23:59:59'];
        }
    }
    if(isset($searchForm['type']) && $searchForm['type']!='-1'){
        $map[] = ['type','=',$searchForm['type']];
    }
    if(isset($searchForm['user_id']) && $searchForm['user_id']!='-1'){
        $map[] = ['user_id','=',$searchForm['user_id']];
    }

	$res = Db::table('point_water')
            ->limit($page,$pageSize)
            ->where($map)
            ->whereNull('delete_time')
            ->select()
            ->all();
    
	foreach($res as $k=>$v){
		$res[$k]['goods_name'] = Db::table('goods')
		->where('id',$v['goods_id'])
		->value('goods_name');
        $res[$k]['nick_name'] = Db::table('users')
		->where('id',$v['user_id'])
		->value('nick_name');
	}
    $count = Db::table('point_water')
            ->where($map)
            ->whereNull('delete_time')
            ->count();
    $dd = [
        'count'=>$count,
        'result'=>$res,
    ];
        
	return $this->returnJson(200,'操作成功',$dd);
  }
  // 获取合作商积分明细
  public function getPointExchangeDetailHzs()
  {
      $param = Request::param();
    $page=$param['page'];
    $pageSize = $param['pageSize'];
    $page=($page-1)*$pageSize;
    $searchForm = $param['searchForm'];
    $map = [];
    if(isset($searchForm['start_time']) && isset($searchForm['end_time'])){
        if($searchForm['start_time']!='' && $searchForm['end_time']!=''){
            $map[] = ['add_time','>=',$searchForm['start_time'].' 00:00:00'];
             $map[] = ['add_time','<=',$searchForm['end_time'].' 23:59:59'];
        }
    }
    if(isset($searchForm['type']) && $searchForm['type']!='-1'){
        $map[] = ['type','=',$searchForm['type']];
    }
    if(isset($searchForm['user_id']) && $searchForm['user_id']!='-1'){
        $map[] = ['user_id','=',$searchForm['user_id']];
    }

	$res = Db::table('point_water_hzs')
            ->limit($page,$pageSize)
            ->where($map)
            ->whereNull('delete_time')
            ->select()
            ->all();
    
	foreach($res as $k=>$v){
		$res[$k]['goods_name'] = Db::table('goods')
		->where('id',$v['goods_id'])
		->value('goods_name');
        $res[$k]['nick_name'] = Db::table('users')
		->where('id',$v['user_id'])
		->value('nick_name');
	}
    $count = Db::table('point_water_hzs')
            ->where($map)
            ->whereNull('delete_time')
            ->count();
    $dd = [
        'count'=>$count,
        'result'=>$res,
    ];
        
	return $this->returnJson(200,'操作成功',$dd);
  }
  // 修改合作商提现状态
  public function updateCooperationWithdrawApply(){
    $param = Request::param();
    $id = $param['id'];
    $status = $param['status'];
    Db::name('reward_history')
            ->where('id',$id)
            ->update(['status'=>$status]);
    $this->returnJson(200,'操作成功',[]);
  }
   // 合作商提现记录 
  public function getCooperationWithdrawApply()
  {
	// 加上分页
	$param = Request::param();
    $searchForm = $param['searchForm'];
	$page=$param['page'];
    $pageSize = $param['pageSize'];
    $page=($page-1)*$pageSize;
    $map = [];
    // if(isset($searchForm['start_time']) && isset($searchForm['end_time'])){
    //     if($searchForm['start_time']!='' && $searchForm['end_time']!=''){
    //         $map[] = ['add_time','>=',$searchForm['start_time'].' 00:00:00'];
    //          $map[] = ['add_time','<=',$searchForm['end_time'].' 23:59:59'];
    //     }
    // }
    if(isset($searchForm['user_id']) && $searchForm['user_id']!=''){
        $map[] = ['user_id','=',$searchForm['user_id']];
    }
    if(isset($searchForm['s_user_id']) && $searchForm['s_user_id']!=''){
        $map[] = ['s_user_id','=',$searchForm['s_user_id']];
    }
    if(isset($searchForm['type']) && $searchForm['type']!='-1'){
        $map[] = ['type','=',$searchForm['type']];
    }
    if(isset($searchForm['status']) && $searchForm['status']!='-1'){
        $map[] = ['status','=',$searchForm['status']];
    }
    if(isset($searchForm['qr_sn']) && $searchForm['qr_sn']!=''){
        $map[] = ['qr_sn','like','%'.$searchForm['qr_sn'].'%'];
    }

  	$res = Db::table('reward_history')
		->order('id','desc')
  		->where($map)
		->limit($page,$pageSize)
		->whereNull('delete_time')
  		->select()
		->all();
    foreach($res as $k=>$v){
        // $v 里边的user_id 的nick_name phone 省市区 地址
		$user = Db::table('users')
        ->field('nick_name,phone,province,city,area,address_info')
        ->where('id',$v['user_id'])
        ->find();
		$res[$k]['nick_name'] = $user['nick_name'];
		if($v['s_user_id']!=''){
            $suser = Db::table('users')
            ->field('nick_name,phone,province,city,area,address_info')
            ->where('id',$v['s_user_id'])
            ->find();
            $res[$k]['s_nick_name'] = $suser['nick_name'];
        } 
    }	

	$count = Db::table('reward_history')
        ->where($map)
        ->whereNull('delete_time')
        ->count();
     return   $this->returnJson(200,'操作成功',
        [
            'result'=>$res,
            'count'=>$count,
        ]
    );
  }
  // 扫码记录
  public function getScanRecord()
  {
    $param = Request::param();
    $searchForm = $param['searchForm'];
	$page=$param['page'];
    $pageSize = $param['pageSize'];
    $page=($page-1)*$pageSize;
    $map = [];
    
    if(isset($searchForm['user_id']) && $searchForm['user_id']!=''){
        $map[] = ['user_id','=',$searchForm['user_id']];
    }
    if(isset($searchForm['qr_sn']) && $searchForm['qr_sn']!=''){
        $map[] = ['qr_sn','like','%'.$searchForm['qr_sn'].'%'];
    }
    if(isset($searchForm['role']) && $searchForm['role']!='-1'){
        $map[] = ['role','=',$searchForm['role']];
    }
    if(isset($searchForm['type']) && $searchForm['type']!='-1'){
        $map[] = ['type','in',$searchForm['type']];
    }
    
    if(isset($searchForm['start_time']) && isset($searchForm['end_time'])){
        if($searchForm['start_time']!='' && $searchForm['end_time']!=''){
            $map[] = ['add_time','>=',$searchForm['start_time'].' 00:00:00'];
             $map[] = ['add_time','<=',$searchForm['end_time'].' 23:59:59'];
        }
    }

     $res = Db::table('write_off_history')
        ->order('id','desc')
        ->where($map)
        ->limit($page,$pageSize)
        ->whereNull('delete_time')
        ->select()
        ->all();
    foreach($res as $k=>$v){
        // $v 里边的user_id 的nick_name phone 省市区 地址
		$user = Db::table('users')
        ->field('nick_name,phone,province,city,area,address_info')
        ->where('id',$v['user_id'])
        ->find();
		$res[$k]['nick_name'] = $user['nick_name'];
    }	
    $count = Db::table('write_off_history')
        ->where($map)
        ->whereNull('delete_time')
        ->count();
    return   $this->returnJson(200,'操作成功',
        [
            'result'=>$res,
            'count'=>$count,
        ]
    );
 }
 // 获取扫码参与人员
 public function getHomeData()
 {
    // 查询  write_off_history表 不要重复的user_id
    
    // 已经参与的人数   
    $yicanyu = Db::name('write_off_history')
        ->whereNull('delete_time')
        ->group('user_id')  // 按user_id分组，确保每个user_id只统计一次
        ->count();
    // 所有用户人数
    $user_count = Db::name('users')
        ->whereNull('delete_time')
        ->count();
    // 未参与的人数
    $un_count = $user_count-$yicanyu;

     // 查询商品列表
     $goods_list = Db::name('award')
        ->whereNull('delete_time')
        ->select()
        ->all();
    foreach($goods_list as $k=>$v){
        $goods_list[$k]['value'] = Db::name('award_history')
        ->where('aid',$v['id'])
        ->whereNull('delete_time')
        ->count();
    }
    
    // 我现在要查users 表中 area字段 个字段的数量
    $areaList = Db::name('users')
        ->distinct(true)  // 开启去重
        ->field('city')  // 指定需要去重的字段（必须指定，否则对所有字段组合去重）
        ->whereNull('delete_time')
        ->select()
        ->all();
    foreach($areaList as $k=>$v1){
        $areaList[$k]['count'] = Db::name('users')
        ->where('city',$v1['city'])
        ->whereNull('delete_time')
        ->count();
        // $v1['count'] = Db::name('users')
        // ->where('area',$v1['area'])
        // ->count();
    }
    return $this->returnJson(200,'操作成功',
        [
            'yicanyu'=>$yicanyu,
            'user_count'=>$user_count,
            'un_count'=>$un_count,
            'goods_list'=>$goods_list,
            'areaList'=>$areaList,
        ]
    );

    
 }
 // 修改公司信息
	public function setCompanInfo()
	{
		$param = Request::param();
		$param['update_time'] = date("Y-m-d H:i:s");
        $id = $this->getAdminId();
		Db::name('yh_company')->where('id',$id)->update($param);
		$this->returnJson(200,'操作成功',[]);
	}
	// 获取设置
	// 获取公司信息
	public function getCompanyInfo()
	{
		$param = Request::param();
        $id = $this->getAdminId();
		$res = Db::name('yh_company')
			->field('id,name,company_name,phone,uname,address,logo')
			->where('id',$id)
			->find();
		$this->returnJson(200,'操作成功',$res);
	}
    // 内定奖品
    public function setInnerAward()
    {
        $param = Request::param();
        $param['update_time'] = date("Y-m-d H:i:s");
        $a_name = Db::name('award')
        ->where('id',$param['aid'])
        ->value('name');
        Db::name('qrcode')->where('id',$param['id'])
            ->update([
                'aid'=>$param['aid'],
                'a_name'=>$a_name,
            ]);
        $this->returnJson(200,'操作成功',[]);
    }
    
}
